package com.imis.base.util;

import cn.hutool.core.util.StrUtil;
import com.imis.base.constant.HttpHeadersConstants;
import com.imis.base.constant.enums.SysTipEnum;
import com.imis.base.globle.CustomizeException;
import com.imis.base.shiro.util.JwtUtil;
import com.imis.module.system.model.vo.SysUserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * CurrentUserUtils<br>
 * 获取当前用户相关 工具类
 * </p>
 *
 * @author XinLau
 * @version 1.0
 * @since 2020年04月19日 10:08
 */
@Slf4j
public class CurrentUserUtils {

    /**
     * 根据request中的token获取用户账号
     *
     * @return String - 用户账号
     * @throws CustomizeException
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/3/10 13:30
     */
    public static String getUserNameByToken() throws CustomizeException {
        String accessToken = SpringContextUtils.getHttpServletRequest().getHeader(HttpHeadersConstants.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(accessToken);
        if (StrUtil.isEmpty(username)) {
            throw new CustomizeException(SysTipEnum.USER_LOGIN_ERR_NON.getValue());
        }
        return username;
    }

    /**
     * 获取当前访问对象的IP地址
     *
     * @return String
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/3/10 13:30
     */
    public static String getUserIp() {
        // 获取request
        HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
        if (ConvertUtils.isEmpty(request)) {
            return null;
        }
        return IPUtils.getClientIpAddress(request);
    }

    /**
     * 获取当前访问对象
     *
     * @return Subject
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/3/10 13:30
     */
    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    /**
     * 获取当前登录用户的基本信息
     *
     * @return SysUserVO
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/3/10 13:30
     */
    public static SysUserVO getLoginUser() {
        SysUserVO sysUser;
        try {
            sysUser = getSubject() == null ? null : (SysUserVO) getSubject().getPrincipal();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            sysUser = null;
        }
        return sysUser;
    }

    /**
     * 获取当前登录用户的编号
     *
     * @return loginUserId
     * @author XinLau
     * @creed The only constant is change ! ! !
     * @since 2020/3/10 13:30
     */
    public static Long getLoginUserId() {
        return getLoginUser() == null ? null : Long.valueOf(getLoginUser().getId());
    }

}
